import React from "react";
import { Tabs, Space, Input, DatePicker, Select, Form, Button } from "antd";
import TheButton from "@/components/TheButton";
import TheTable from "@/components/TheTable";
import ThePagination from "@/components/ThePagination";
import "@/views/commodity/style/style.less";
import { apiGetOrderList, apiGetPersonnelList, apiGetSendOrders, apiOnlineExportCapitalDaily, apiOnlineExportOrderDetail } from '@/request/orderManagement'
import { apiExportLibraryOutReport, } from '@/request/cashier'
import store from "@/store/store"

import { getDateTime3 } from '@/utils/getDate'
import TheDialog from '@/components/TheDialog'
import { exportTable, exportSheetTable } from '@/utils/exportTable.js'
import moment from "moment";

const { RangePicker } = DatePicker;
const { Search } = Input;
const { TabPane } = Tabs;

class OrderList extends React.Component {
  state = {
    exportLoading: false,
    orderState: '3',
    columns2: [
      {
        title: "订单编号",
        dataIndex: "orderCode",
        key: "orderCode",
      },
      {
        title: "用户昵称",
        dataIndex: "orderMemberName",
        key: "orderMemberName",
      },
      {
        title: "订单金额（元）",
        dataIndex: "orderTotalPrice",
        key: "orderTotalPrice",
        render: (text, render) => {
          return <React.$Price price={render.orderTotalPrice} />
        }
      },
      {
        title: "实付金额（元）",
        dataIndex: "orderPayPrice",
        key: "orderPayPrice",
        render: (text, render) => {
          return <React.$Price price={render.orderPayPrice} />
        }
      },
      {
        title: "付款方式",
        dataIndex: "payWay",
        key: "payWay",
        render: (text, render) => {
          let label = ''
          switch (render.payWay) {
            case 'WeChat':
              label = '微信'
              break;
            case 'Alipay':
              label = '支付宝'
              break;
            case 'UnionPay':
              label = "银联"
              break;
            case 'YsPay':
              label = "银行卡支付"
              break;
              case 'RemoteAlipay':
                label = "扫码支付（支付宝）"
                break;
            case 'RemoteWeChat':
              label = "扫码支付（微信）"
                break;
            default:
              label = "未知支付方式"
          }
          return label;
        }
      },
      {
        title: "收货方式",
        dataIndex: "pickupWay",
        key: "pickupWay",
        render: (text, render) => {
          let label = ""
          switch (render.pickupWay) {
            case 'D':
              label = "到店自取"
              break;
            case 'T':
              label = '同城配送'
              break
            default:
              label = "未知配送方式"
          }
          return label;
        }
      },
      {
        title: "订单时间",
        dataIndex: "createTime",
        key: "createTime",
      },
      {
        title: "订单状态",
        render: () => {
          return '未使用'
        }
      },
      {
        title: "操作",
        fixed: "right",
        render: (text, render) => {
          return (
            <div>
              <TheButton
                hasPermi={['order:list:detail']}
                onClick={() => this.props.history.push(`/order/details/${render.orderId}`)}
              >
                查看订单
              </TheButton>
            </div>
          );
        },
      },
    ],
    columns3: [
      {
        title: "订单编号",
        dataIndex: "orderCode",
        key: "orderCode",
      },
      {
        title: "用户昵称",
        dataIndex: "orderMemberName",
        key: "orderMemberName",
      },
      {
        title: "订单金额（元）",
        dataIndex: "orderTotalPrice",
        key: "orderTotalPrice",
        render: (text, render) => {
          return <React.$Price price={render.orderTotalPrice} />
        }
      },
      {
        title: "实付金额（元）",
        dataIndex: "orderPayPrice",
        key: "orderPayPrice",
        render: (text, render) => {
          return <React.$Price price={render.orderPayPrice} />
        }
      },
      {
        title: "付款方式",
        dataIndex: "payWay",
        key: "payWay",
        render: (text, render) => {
          let label = ''
          switch (render.payWay) {
            case 'WeChat':
              label = '微信'
              break;
            case 'Alipay':
              label = '支付宝'
              break;
            case 'UnionPay':
              label = "银联"
              break;
            case 'YsPay':
              label = "银行卡支付"
              break;
              case 'RemoteAlipay':
                label = "扫码支付（支付宝）"
                break;
            case 'RemoteWeChat':
              label = "扫码支付（微信）"
                break;
            default:
              label = "未知支付方式"
          }
          return label;
        }
      },
      {
        title: "收货方式",
        dataIndex: "pickupWay",
        key: "pickupWay",
        render: (text, render) => {
          let label = ""
          switch (render.pickupWay) {
            case 'D':
              label = "到店自取"
              break;
            case 'T':
              label = '同城配送'
              break
            default:
              label = "未知配送方式"
          }
          return label;
        }
      },
      {
        title: "订单时间",
        dataIndex: "createTime",
        key: "createTime",
      },
      {
        title: "订单状态",
        render: (text, record) => {
          return record.deliveryState === 'Y' ? '已派送' : record.deliveryState === 'N' ? '待派单' : '未知订单状态'
        }
      },
      {
        title: "操作",
        fixed: "right",
        render: (text, render) => {
          return (
            <div>
              <TheButton
                hasPermi={['order:list:detail']}

                onClick={() => this.props.history.push(`/order/details/${render.orderId}`)}
              >
                查看订单
              </TheButton>
              {render.deliveryState === 'N' && <TheButton hasPermi={['order:list:sendOrder']} onClick={() => this.setState({ visible: true, orderId: render.orderId })}>派单</TheButton>}
            </div>
          );
        },
      },
    ],
    columns9: [
      {
        title: "订单编号",
        dataIndex: "orderCode",
        key: "orderCode",
      },
      {
        title: "用户昵称",
        dataIndex: "orderMemberName",
        key: "orderMemberName",
      },
      {
        title: "订单金额（元）",
        dataIndex: "orderTotalPrice",
        key: "orderTotalPrice",
        render: (text, render) => {
          return <React.$Price price={render.orderTotalPrice} />
        }
      },
      {
        title: "实付金额（元）",
        dataIndex: "orderPayPrice",
        key: "orderPayPrice",
        render: (text, render) => {
          return <React.$Price price={render.orderPayPrice} />
        }
      },
      {
        title: "付款方式",
        dataIndex: "payWay",
        key: "payWay",
        render: (text, render) => {
          let label = ''
          switch (render.payWay) {
            case 'WeChat':
              label = '微信'
              break;
            case 'Alipay':
              label = '支付宝'
              break;
            case 'UnionPay':
              label = "银联"
              break;
            case 'YsPay':
              label = "银行卡支付"

              break;
              case 'RemoteAlipay':
                label = "扫码支付（支付宝）"
                break;
            case 'RemoteWeChat':
              label = "扫码支付（微信）"
                break;
            default:
              label = "未知支付方式"
          }
          return label;
        }
      },
      {
        title: "收货方式",
        dataIndex: "pickupWay",
        key: "pickupWay",
        render: (text, render) => {
          let label = ""
          switch (render.pickupWay) {
            case 'D':
              label = "到店自取"
              break;
            case 'T':
              label = '同城配送'
              break
            default:
              label = "未知配送方式"
          }
          return label;
        }
      },
      {
        title: "订单时间",
        dataIndex: "createTime",
        key: "createTime",
      },
      {
        title: "订单状态",
        render: () => {
          return '已使用'
        }
      },
      {
        title: "使用时间",
        dataIndex: "finishTime",
        key: "finishTime",
      },
      {
        title: "操作",
        fixed: "right",
        render: (text, render) => {
          return (
            <div>
              <TheButton
                hasPermi={['order:list:detail']}
                onClick={() => this.props.history.push(`/order/details/${render.orderId}`)}
              >查看订单</TheButton>
            </div>
          );
        },
      },
    ],
    dataSource2: [],
    dataSource3: [],
    dataSource9: [],
    pageData2: {
      pageNo: 1,
      pageSize: 10,
    },
    pageData3: {
      pageNo: 1,
      pageSize: 10,
    },
    pageData9: {
      pageNo: 1,
      pageSize: 10,
    },
    total2: 0,
    total3: 0,
    total9: 0,
    tabData: [
      {
        label: '待接单',
        value: '3'
      },
      {
        label: '未使用',
        value: '2'
      },
      {
        label: '已使用',
        value: '9'
      },
    ],
    searchValue: {
      orderMemberName: '',
      orderTypeName: '',
      orderCode: '',
      createTimeStart: '',
      createTimeEnd: ''
    },
    visible: false,
    options: [],
    loading: false
  };
  async componentDidMount() {
    let searchParams = store.getState().searchValue
    if (searchParams) {
      let { pageNo, pageSize, orderState, searchValue } = searchParams
      this.setState({
        orderState: orderState ? orderState : '3',
        searchValue: {
          ...searchParams
        },
        [`pageData${orderState}`]: {
          pageNo: pageNo, pageSize: pageSize
        }
      }, () => {

        this.getData()
      })
    } else {
      this.getData()

    }
    await this.getOptions()
  }
  getOptions = async () => {
    let res = await apiGetPersonnelList({ status: 'Y' })
    if (res.data && res.code === 0) {
      let options = res.data.map(v => {
        return {
          value: v.verificationPersonnelId,
          label: v.userName
        }
      })
      this.setState({ options })
    }
  }
  // 导出资金日报
  onlineExportCapitalDaily = async () => {
    this.setState({ exportLoading: true })
    let res = await apiOnlineExportCapitalDaily({ ...this.state.searchValue })
    if (res.code === 0 && res.data) {
      const th_arr = [
        {
          title: '日期',
          prop: 'day'
        },
        {
          title: '计算方式',
          prop: '',
          children: res.data.payWay.map(item => {
            return {
              title: item.remark,
              prop: item.value,valueType:'number'
            }
          })
        }
        ,
        {
          title: '服务收入',
          prop: 'service',valueType:'number'
        },
        {
          title: '商品收入',
          prop: 'good',valueType:'number'
        },

        {
          title: '退款',
          prop: 'back',valueType:'number'
        },

        {
          title: '总收入',
          prop: 'total',valueType:'number'
        }]
      th_arr[1].children.push({
        title: "小计",
        prop: "paywayPrice",valueType:'number'
      })
      const tb_arr = res.data.data.map(item => {
        return {
          ...item,
          paywayPrice: Number(item.paywayPrice).toFixed(2),

          total: Number(item.total).toFixed(2) || '0'

        }
      })
      this.setState({ exportLoading: false })
      exportSheetTable({ fileName: '资金日报', tH_data: th_arr, tB_data: tb_arr, isSheet: true, merge: false, mergeProp: [] })
    }
  }
  // 导出资金日报订单
  onlineExportOrderDetail = async () => {
    this.setState({ exportLoading: true })

    let res = await apiOnlineExportOrderDetail({ ...this.state.searchValue })
    if (res.code === 0 && res.data) {
      let payWay = {}
      res.data.payWay.forEach(item => {
        payWay[item.value] = item.remark
      })
      const th_arr = [
        {
          title: '资金日报订单',
          prop: '',
          children: [
            {
              title: '订单编号',
              prop: 'orderCode'
            },
            {
              title: '用户昵称',
              prop: 'orderMemberName'
            },
            {
              title: '商品名称',
              prop: 'productName',
            },

            {
              title: '规格',
              prop: 'sku',
            },
            {
              title: '商品价格',
              prop: 'orderPrice',valueType:'number'
            },
            {
              title: '付款方式',
              prop: 'payWay'
            },
            {
              title: '付款金额',
              prop: 'orderTotalPrice',valueType:'number'
            },
            {
              title: '退款',
              prop: 'refundPrice',valueType:'number'
            },
            {
              title: '实收金额',
              prop: 'realityPayPrice',valueType:'number'
            },
            {
              title: '付款时间',
              prop: 'createTime'
            },
          ]
        },

      ]
      let tb_arr = []
      res.data.data.forEach(item => {
        for(let i=0; i<res.data.payWay.length; i++){
          if(item.orderPayWay === res.data.payWay[i].value){
            item.payWay = res.data.payWay[i].name
          }
        }
        item.orderDetails.forEach(item2 => {
          tb_arr.push({
            orderCode: item.orderCode || '/',
            orderMemberName: item.orderMemberName || '/',
            productName: item2.productName || '/',
            sku: item2.sku || '/',
            orderPrice: Number(item2.orderPrice).toFixed(2) || '0',
            payWay: item.payWay || '/',
            orderTotalPrice: Number(item.orderTotalPrice).toFixed(2) || '/',
            refundPrice: Number(item.refundPrice).toFixed(2) || '0',
            realityPayPrice: Number(item.realityPayPrice).toFixed(2) || '0',
            createTime: item.day || '/'
          })
        })
      })
      this.setState({ exportLoading: false })
      const mergeProp = [
        { key: 'orderMemberName' },
        { key: 'orderCode' },
        { key: 'refundPrice' },
        { key: 'payWay' },
        { key: 'orderTotalPrice' },
        { key: 'createTime' },
        { key: 'realityPayPrice' }
      ]
      exportSheetTable({
        fileName: '资金日报订单', tH_data: th_arr, tB_data: tb_arr, isSheet: true, merge: true, mergeProp
      })
    }
  }
  exportSaleOutTable = async (option) => {
    let res = await apiExportLibraryOutReport({
      ...this.state.searchValue
    })
    if (res.code === 0 && res.data) {
      const th_arr = [
        {
          title: '序号',
          prop: 'productId'
        },
        {
          title: '日期',
          prop: 'day'
        },
        {
          title: '物料Id',
          prop: 'materialId',
        },
        {
          title: '库存单位',
          prop: 'unit'
        },
        {
          title: '实发数量',
          prop: 'orderProductCount',valueType:'number'
        },
        {
          title: '含税单价',
          prop: 'orderPrice',
          valueType:'number'
        }
      ]
      const tb_arr = res.data
      exportSheetTable({ fileName: '销售出库单', tH_data: th_arr, tB_data: tb_arr, isSheet: true })

    }
  }
  getData = async () => {
    this.setState({ loading: true })
    const { orderState, searchValue } = this.state
    let params = {
      ...searchValue,
      orderState,
      ...this.state[`pageData${orderState}`]
    }

    store.dispatch({
      type: 'SaveSearchValues',
      data: {
        ...params
      }
    })
    let res = await apiGetOrderList({
      ...params
    })
    if (res.data && res.code === 0) {
      this.setState({
        [`pageData${orderState}`]: {
          pageNo: res.pageNo,
          pageSize: res.pageSize
        },
        [`dataSource${orderState}`]: res.data,
        [`total${orderState}`]: res.totalCount,
        loading: false
      })
    }
  }
  setTabKey = (orderState) => {
    this.setState({ orderState }, () => {

      this.getData()
    })
  };
  pageChange = (pageNo, pageSize, index) => {
    this.setState({
      [`pageData${index}`]: {
        pageNo,
        pageSize,
      },
    }, () => {
      let search = JSON.stringify(this.state.searchValue)

      this.getData()
    });
  };
  setNickName = e => {
    this.setState({
      searchValue: {
        ...this.state.searchValue,
        memberName: e
      },
      pageData2: {
        pageNo: 1,
        pageSize: 10
      },
      pageData3: {
        pageNo: 1,
        pageSize: 10
      },
      pageData9: {
        pageNo: 1,
        pageSize: 10
      },
    }, () => {
      this.getData()
    })
  }
  setStoreName = e => {
    this.setState({
      searchValue: {
        ...this.state.searchValue,
        storeName: e
      },
      pageData2: {
        pageNo: 1,
        pageSize: 10
      },
      pageData3: {
        pageNo: 1,
        pageSize: 10
      },
      pageData9: {
        pageNo: 1,
        pageSize: 10
      },
    }, () => {

      this.getData()
    })
  }
  setOrderCode = e => {
    console.log(e, 'e');
    this.setState({
      searchValue: {
        ...this.state.searchValue,
        orderCode: e
      },
      pageData2: {
        pageNo: 1,
        pageSize: 10
      },
      pageData3: {
        pageNo: 1,
        pageSize: 10
      },
      pageData9: {
        pageNo: 1,
        pageSize: 10
      },
    }, () => {

      this.getData()
    })
  }
  datePickerChange = e => {

    if (e) {
      this.setState({
        searchValue: {
          ...this.state.searchValue,
          createTimeStart: getDateTime3(e[0]),
          createTimeEnd: getDateTime3(e[1])
        },
        pageData2: {
          pageNo: 1,
          pageSize: 10
        },
        pageData3: {
          pageNo: 1,
          pageSize: 10
        },
        pageData9: {
          pageNo: 1,
          pageSize: 10
        },
      }, () => {

        this.getData()
      })
    } else {
      this.setState({
        searchValue: {
          ...this.state.searchValue,
          createTimeStart: '',
          createTimeEnd: ''
        },
        pageData2: {
          pageNo: 1,
          pageSize: 10
        },
        pageData3: {
          pageNo: 1,
          pageSize: 10
        },
        pageData9: {
          pageNo: 1,
          pageSize: 10
        },
      }, () => {
        this.getData()
      })
    }
  }
  closeDialog = () => {
    this.setState({
      visible: false,
      orderId: '',
      btnLoading: false
    })
  }
  sendOrder = async value => {
    this.setState({ btnLoading: true })
    let { orderId } = this.state
    let res = await apiGetSendOrders({ orderId, ...value })
    if (res.code === 0) {
      React.$message({
        type: 'info',
        content: '派单成功'
      })
      this.closeDialog()
      this.getData()
    }
  }
  changeParams(e, key) {
    console.log(e, ';eee');
    this.setState({
      searchValue: {
        ...this.state.searchValue,
        [key]: e.target.value
      }
    })
  }
  render() {
    const { searchValue } = this.state
    const orderCode = searchValue.orderCode
    const memberName = searchValue.memberName

    const operations = {
      right: (
        <Space>

          <Search
            value={memberName}
            onChange={(e) => this.changeParams(e, 'memberName')}
            onSearch={(e) => this.setNickName(e)}
            style={{ width: 150 }}
            placeholder={"用户昵称"}
            allowClear
            enterButton
          />
          {/* <Search
            onSearch={(e) => this.setStoreName(e)}
            style={{ width: 150 }}
            placeholder={"门店名称"}
            allowClear
            enterButton
          /> */}
          <Search
            value={orderCode}
            onChange={(e) => this.changeParams(e, 'orderCode')}
            onSearch={(e) => this.setOrderCode(e)}
            style={{ width: 180 }}
            placeholder={"请输入订单号"}
            allowClear
            enterButton
          />
          <div>
            <span>下单时间 </span>
            <RangePicker value={searchValue.hasOwnProperty('createTimeStart') && searchValue.createTimeStart ? [moment(searchValue.createTimeStart, 'YYYY/MM/DD'), moment(searchValue.createTimeEnd, 'YYYY/MM/DD')] : []} format={'YYYY/MM/DD'} onChange={(e) => this.datePickerChange(e)} />
          </div>
          <TheButton size="middle" type="default" hasPermi={['order:list:exportDaily']} onClick={this.onlineExportCapitalDaily} loading={this.exportLoading}>导出资金日报</TheButton>
          <TheButton size="middle" type="default" hasPermi={['order:list:exportDailyOrder']} onClick={this.onlineExportOrderDetail} loading={this.exportLoading}>导出资金日报订单</TheButton>
          <TheButton size="middle" type="default" hasPermi={['order:list:exportSales']} onClick={this.exportSaleOutTable} loading={this.exportLoading}>导出销售出库单</TheButton>
        </Space>

      ),
    };
    const { tabData, visible, options, btnLoading, loading, orderState } = this.state;
    return (
      <div className="p-layout-box">
        <Tabs
          activeKey={`${orderState}`}
          onChange={(value) => this.setTabKey(value)}
          tabBarExtraContent={operations}
        >
          {tabData.map((v, i) => {
            return (
              <TabPane tab={v.label} key={v.value} >
                <div className="p-layout-content-pagination">
                  <TheTable
                    scroll={{ x: "max-content" }}
                    columns={this.state[`columns${v.value}`]}
                    dataSource={this.state[`dataSource${v.value}`]}
                    loading={loading}
                  />
                  <ThePagination
                    pageNo={this.state[`pageData${v.value}`].pageNo}
                    pageSize={this.state[`pageData${v.value}`].pageSize}
                    total={this.state[`total${v.value}`]}
                    pageChange={(pageNo, pageSize) =>
                      this.pageChange(pageNo, pageSize, v.value)
                    }
                  />
                </div>
              </TabPane>
            );
          })}
        </Tabs>
        <TheDialog
          title="选择核销员"
          footer={null}
          handleCancel={this.closeDialog}
          visible={visible}
          width={400}
        >
          <Form onFinish={this.sendOrder}>
            <Form.Item name="verificationUserId" label="选择核销员" rules={[{ required: true }]}>
              <Select allowClear options={options} placeholder="选择核销员" />
            </Form.Item>
            <Form.Item>
              <div style={{ width: '100%', display: 'flex', justifyContent: 'flex-end', marginBottom: -30 }}>
                <Space>
                  <Button onClick={this.closeDialog}>取消</Button>
                  <Button loading={btnLoading} type="primary" htmlType="submit">确定</Button>
                </Space>
              </div>
            </Form.Item>
          </Form>
        </TheDialog>
      </div>
    );
  }
}

export default OrderList;
